<?php

namespace App\Http\Controllers\Innerend;

use App\Models\User;
use App\Service\Tree;
use App\Models\SiteCate;

class SiteCateController extends BaseController
{
    protected $channel;

    // 栏目管理
    public function initialize()
    {
        parent::initialize();

        $this->assign('is_tree_page',true);
        $this->model = 'SiteCate';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        // 树状制作
        $tree  = new Tree();
        $lists = $tree->toList($lists); // 树状

        // 数字
        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid     = $item['uid'];
            $_user    = $users[$_uid] ?? [];
            $_id      = $item['id'];
            $status   = $item['status'] == 1 ? '正常' : '禁用';
            $statusOp = $item['status'] == 1 ? '禁用' : '启用';

            // 子级
            $levelHtml = $item['level'] ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $item['level']).'|--' : '';

            // 操作
            $operate = $listHtml->operate_status(['id' => $_id, 'status' => 1 - $item['status']], $statusOp, $item['status']);
            $operate .= $listHtml->operate_edit(['id' => $_id], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该分类吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($levelHtml.$item['title'], 'left');
            $tr .= $listHtml->list_td($_user['username'] ?? '-');
            $tr .= $listHtml->list_td($item['keyword']);
            $tr .= $listHtml->list_td($status);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        // 'pid' => ['标题',250],
        return ['title' => ['栏目名称', 200], 'uid' => ['绑定用户', 120], 'keyword' => '关键字', 'status' => ['状态', 80], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 父级
        // 树状制作
        $model  = new SiteCate();
        $where  = [['status', '>=', 0],];
        $lists  = $model->isCache(true)->getAll($where, 'rank ASC');
        $lists  = (new Tree())->toList($lists); // 树状
        $parent = $form->formSelectLists('pid', $info['pid'] ?? '0', $lists, 'id', 'title');

        // 用户名
        $username = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');

        $status  = $form->formRadio('status', $info['status'] ?? 1, [1 => '正常', 0 => '禁用']);
        $title   = $form->formInput('title', $info['title'] ?? '', '栏目名称');
        $keyword = $form->formTextarea('keyword', $info['keyword'] ?? '', '关键字');
        $_id     = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('父级', $parent);
        $html .= $form->makeItem('栏目名称', $title);
        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('重要性', $status);
        $html .= $form->makeItem('关键字', $keyword);
        $html .= $_id;

        return $html;
    }

    // 列表搜索
    protected function list_search()
    {
        $search = [];  // keyword
        $this->assign('search', $search);

        $searchHide = ['channel'];
        $this->assign('searchHide', []);
    }

    // 返回列表数据
    public function onLists()
    {
        $where = $this->listWhere();
        $model = new SiteCate();

        // 查询（列表展示）
        $lists  = $model->isCache(true)->getAll($where, 'rank ASC');
        $lists  = is_object($lists) ? $lists->toArray() : $lists;
        $result = $this->listTable($lists);

        return $this->success($result);
    }


    // 排序
    public function onRank()
    {
        $_value = $this->getData('rank', 0, 'intval');
        $this->throwIf(is_null($_value), '请填写排序数字！');

        return $this->changeField('rank', $_value);
    }

    // 启用禁用
    public function onStatus()
    {
        $_value = $this->getData('status', null, 'intval');
        $this->throwIf(is_null($_value), '是否启用状态必须填写！');
        $this->throwIf(!in_array($_value, [0, 1]), '是否启用状态必须为0或1！');

        return $this->changeField('status', $_value);
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['status' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表查询
    protected function listWhere()
    {
        $where   = [['status', '>=', 0],]; // ['pid', '=', 0]
        $keyword = $this->getData('keyword', null, 'trim');
        if($keyword){
            $where[] = $this->orWhere('title|keyword|description', 'like', $keyword);
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            //'id'          => $this->getData("id", 0, 'intval'),
            'rank'        => $this->getData("rank", 0, 'intval'),
            'title'       => $this->getData("title", '', 'trim'),
            'pid'         => $this->getData("pid", 0, 'intval'),
            'status'      => $this->getData("status", 1, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            //'ctime'       => $this->getData("ctime", 0, 'intval'),
            //'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            //'id'          => $this->getData("id", 0, 'intval'),
            'rank'        => $this->getData("rank", 0, 'intval'),
            'title'       => $this->getData("title", '', 'trim'),
            'pid'         => $this->getData("pid", 0, 'intval'),
            'status'      => $this->getData("status", 1, 'intval'),
            'uid'         => $this->getData("uid", 0, 'intval'),
            'keyword'     => $this->getData("keyword", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            //'ctime'       => $this->getData("ctime", 0, 'intval'),
            //'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        // 修改的时候：如果有父级 则父级不能是当前id 也不能是当前id的子级
        if(!empty($data['pid'])){
            $pid = $data['pid'];
            $id  = $this->id;
            $this->throwIf(empty($id), '请指定要修改的记录！');
            $this->throwIf($id == $pid, '修改父级不能是自己！');
            // 获取当前的子级
            $cateDb = new SiteCate();
            $ids    = $cateDb->getChildIds($id);
            $this->throwIf($ids && in_array($pid, $ids), '修改父级不能是自己的子级！');
        }

        return $data;
    }

}


